#include "Inventory.h"

#include "Item.h"

Inventory::Inventory(void): m_iMaxSize(DEFAULT_INVENTORY_SIZE), m_iCurSize(0)
{
}


Inventory::~Inventory(void)
{
   // Clear out our stored items
   map<int, Item *>::iterator itr = m_mItems.begin();
   while (itr != m_mItems.end())
   {
      if ((*itr).second != NULL)
         delete (*itr).second;
      (*itr).second = NULL;
      ++itr;
   }

   m_mItems.clear();
}

int Inventory::AddItem(Item * pItem)
{
   ItemSize iSize = pItem->GetItemSize();

   // Inventory is too full to accept this item, don't add it
   if (m_iCurSize + iSize > m_iMaxSize)
      return -1;

   // Increment our current size and add the item
   m_iCurSize += iSize;

   unsigned int iUID = pItem->GetUniqueID();

   m_mItems[iUID] = pItem;
   return iUID;
}

Item * Inventory::RemoveItem(int iUID, bool bDelete)
{
   map<int, Item*>::iterator itr = m_mItems.find(iUID);
   if (itr != m_mItems.end())
   {
      // This allows us to transfer items between inventories
      Item * pItemToRemove = (*itr).second;
      m_mItems.erase(itr);
      if (bDelete)
      {
         delete pItemToRemove;
         pItemToRemove = NULL;
      }
      return pItemToRemove;
   }
   // Couldn't find an item with that ID in our inventory
   return NULL;
}

Item * Inventory::RemoveItem(char * sItemName, bool bDelete)
{
   map<int, Item*>::iterator itr = m_mItems.begin();

   // Loop through our inventory looking for the first item named sItemName and remove it if we find it
   while (itr != m_mItems.end())
   {
      if (strcmp((*itr).second->GetName(), sItemName) == 0)
         // Pass the remove on to our remove by Unique ID function
         return RemoveItem((*itr).first, bDelete);

      ++itr;
   }
   // Couldn't find an item with that name in our inventory
   return NULL;
}

Item * Inventory::GetItemFromInventory(int iUID)
{
   map<int, Item*>::iterator itr = m_mItems.find(iUID);
   if (itr != m_mItems.end())
      return (*itr).second;

   // Couldn't find an item with that ID in our inventory
   return NULL;
}

Item * Inventory::GetItemFromInventory(char * sName)
{
   map<int, Item*>::iterator itr = m_mItems.begin();

   // Loop through our inventory looking for the first item named sItemName and return it if we find it
   while (itr != m_mItems.end())
   {
      if (strcmp((*itr).second->GetName(), sName) == 0)
      {
         // the Item pointer
         return (*itr).second;
      }
      ++itr;
   }
   // Couldn't find the item, return NULL
   return NULL;
}
